package main

import (
	"log"
	"net"
	"sync"
	"time"
)

const (
	Host = "localhost:9111"
)

type Device struct {
	Conn  net.Conn
	Mutex sync.Mutex
}

// 虚拟设备是tcp协议的设备，需要连接到平台，然后发送数据,如果异常断开，需要重连
func NewDevice() {
	var conn net.Conn
	// 连接到平台
	for {
		c, err := net.Dial("tcp", Host)
		if err != nil {
			log.Println("Error dialing:", err.Error())
			//等待5秒
			time.Sleep(5 * time.Second)
			continue
		} else {
			log.Println("Connected to server")
			conn = c
			break
		}

	}

	device := &Device{
		Conn:  conn,
		Mutex: sync.Mutex{},
	}
	// 模拟设备发送数据
	for {
		device.send()
	}
	//select {}
}

// 断开连接
func (d *Device) Close() {
	d.Conn.Close()
}

// 重新连接
func (d *Device) Reconnect() {
	for {
		c, err := net.Dial("tcp", Host)
		if err != nil {
			log.Println("Error dialing:", err.Error())
			time.Sleep(5 * time.Second)
			continue
		}
		d.Conn = c
		break
	}

}

// 0014*KA,120414,50,100,100,100.12
func (d *Device) SendMessage(messageID string, m string) {
	message := "01c51d170bae18cded99ed56847f3516DW*334588000000156*" + m + "\n"
	d.Mutex.Lock()
	defer d.Mutex.Unlock()
	_, err := d.Conn.Write([]byte(message))
	if err != nil {
		log.Println("Error writing:", err.Error())
		d.Close()
		d.Reconnect()
	}
	log.Println("Message Sent:", message)
	// 读取平台回复
	buf := make([]byte, 1024)
	n, err := d.Conn.Read(buf)
	if err != nil {
		log.Println("Error reading:", err.Error())
		d.Close()
		d.Reconnect()
	} else {
		log.Println("Message Received:", string(buf[:n]))
		//校验回复
		// if string(buf[:n]) != "DW*334588000000156*0002*KA" {
		// 	log.Println("Error message:", string(buf[:n]))
		// 	d.Close()
		// 	d.Reconnect()
		// }
	}

}

func (d *Device) send() {
	go d.SendMessage("KA", "0014*KA,120414,50,100,100,100.12")
	time.Sleep(1 * time.Second)
	go d.SendMessage("ICCID", "001A*ICCID,89860000000000000007")
	time.Sleep(10 * time.Second)
}
